package com.mr.userclient.controller;

import com.mr.userclient.constant.Constant;
import com.mr.userclient.entity.User;
import com.mr.userclient.service.UserService;
import com.mr.userclient.utils.ConstantEnum;
import com.mr.userclient.utils.CookieUtil;
import com.mr.userclient.utils.ResultVOUtil;
import com.mr.userclient.utils.UUIDUtil;
import com.mr.userclient.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * Class: UserController
 * User (作者):MRui
 * TODO (描述)：用户登陆Controller
 * Date 2018-11-15 23:38
 */
@RestController
@Slf4j
@RequestMapping("/login")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
    * User (作者): MRui
    * TODO (描述)：买家登陆
    * Data：2018-11-15 23:42
    */
    @PostMapping("buyer")
    public ResultVO buyer(@RequestParam("openid") String openid,
                          HttpServletResponse response){
        //1查询用户
        User user = userService.findByOpenid(openid);
        if (user == null){
            return ResultVOUtil.error(ConstantEnum.LOGIN_FAIL.getCode(),"登陆失败");
        }
        //2判断角色
        if (ConstantEnum.BUYER.getCode() != user.getRole()){
            return ResultVOUtil.error(ConstantEnum.ROLE_ERROR.getCode(),"登陆失败(角色有误)");
        }
        //3设置Cookie
        CookieUtil.set(response, Constant.OPENID,openid,Constant.OPENID_EXPIRE);

        return ResultVOUtil.success();
    }
    /**
    * User (作者): MRui
    * TODO (描述)：卖家登陆
    * Data：2018-11-15 23:44
    */
    @PostMapping("seller")
    public ResultVO seller(@RequestParam("openid") String openid,
                          HttpServletRequest request,
                          HttpServletResponse response){

        //判断是否已登陆
        Cookie cookie = CookieUtil.get(request, Constant.COOKIE_TOKEN);
        //cookie不为空并且redis能获取到值说明已经登陆
        if(cookie != null && !StringUtils.isEmpty(redisTemplate.opsForValue().get(String.format(Constant.REDIS_TOKEN_PREFIX,cookie.getValue())))){
            return ResultVOUtil.success();
        }
        //1查询用户
        User user = userService.findByOpenid(openid);
        if (user == null){
            return ResultVOUtil.error(ConstantEnum.LOGIN_FAIL.getCode(),"登陆失败");
        }
        //2判断角色
        if (ConstantEnum.SELLER.getCode() != user.getRole()){
            return ResultVOUtil.error(ConstantEnum.ROLE_ERROR.getCode(),"登陆失败(角色有误)");
        }

        //3写入redis设置key=uuid，value
        String token = UUIDUtil.getUUID();
        redisTemplate.opsForValue().set(String.format(Constant.REDIS_TOKEN_PREFIX,token ),//key
                openid,//value
                Constant.REDIS_EXPIRE,//超时时间
                TimeUnit.SECONDS);//时间单位秒
        //4设置Cookie token = UUID
        CookieUtil.set(response, Constant.COOKIE_TOKEN,token,Constant.COOKIE_EXPIRE);
        //验证redis是否生效
        String s = redisTemplate.opsForValue().get(String.format(Constant.REDIS_TOKEN_PREFIX,token ));
        log.info("redis:"+s);
        return ResultVOUtil.success();
    }

}
